import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-02-09
 * Time: 21:12
 */
public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;//左孩子的引用
        public TreeNode right;//右孩子的引用

        public TreeNode(char val) {
            this.val = val;
        }
    }


    /**
     * 创建一棵二叉树 返回这棵树的根节点
     *
     * @return
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        //E.right = H;
        return A;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    // 中序遍历
    void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

    // 后序遍历
    void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    public static int nodeSize;

    /**
     * 获取树中节点的个数：遍历思路
     */
    void size(TreeNode root) {
        if (root == null) {
            return;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    /**
     * 获取节点的个数：子问题的思路
     *
     * @param root
     * @return
     */
    int size2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return size2(root.left) + size2(root.right) + 1;
    }


    /*
     获取叶子节点的个数：遍历思路
     */
    public static int leafSize = 0;

    void getLeafNodeCount1(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    /*
     获取叶子节点的个数：子问题
     */
    int getLeafNodeCount2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    /*
    获取第K层节点的个数
     */
    int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) +
                getKLevelNodeCount(root.right, k - 1);
    }

    /*
     获取二叉树的高度
     时间复杂度：O(N)
     */
    int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return leftH > rightH ? leftH + 1 : rightH + 1;
    }


    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, char val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }

        TreeNode ret = find(root.left, val);
        if (ret != null) {
            return ret;
        }
        ret = find(root.right, val);
        if (ret != null) {
            return ret;
        }
        return null;
    }

    //层序遍历
    void levelOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.println(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }


    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return false;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        TreeNode cur = queue.peek();
        if (cur == null) {
            queue.poll();
        } else {
            return false;
        }
        return true;
    }

    //平衡二叉树
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        return maxDepth(root) >= 0;
    }

    private int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = maxDepth(root.left);
        if (leftH == -1) {
            return -1;
        }
        int rightH = maxDepth(root.right);
        if (leftH >= 0 && rightH >= 0 && Math.abs(rightH - leftH) <= 1) {
            return Math.max(rightH, leftH) + 1;
        } else {
            return -1;
        }
    }

    //另一棵树的子树
    class Solution {
        public boolean isSubtree(TreeNode root, TreeNode subRoot) {
            if (subRoot == null) {
                return true;
            }
            if (root == null) {
                return false;
            }
            if (root.val == subRoot.val && isSame(root, subRoot)) {
                return true;
            }
            return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
        }

        private boolean isSame(TreeNode root, TreeNode subRoot) {
            if (root == null && subRoot == null) {
                return true;
            }
            if (root == null || subRoot == null) {
                return false;
            }
            return root.val == subRoot.val && isSame(root.left, subRoot.left) && isSame(root.right, subRoot.right);
        }
    }

    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return false;
        }
        return isSymmetricChild(root.left, root.right);
    }

    private boolean isSymmetricChild(TreeNode Rleft, TreeNode Rright) {
        if ((Rleft != null && Rright == null) || (Rleft == null && Rright != null)) {
            return false;
        }
        if (Rleft == null && Rright == null) {
            return true;
        }
        if (Rleft.val != Rright.val) {
            return false;
        }
        return isSymmetricChild(Rleft.left, Rright.right) && isSymmetricChild(Rleft.right, Rright.left);
    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        if (root.left == null && root.right == null) {
            return root;
        }

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    //二叉树的层序遍历
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            List<Integer> curList = new ArrayList<Integer>();
            int size = queue.size();
            while (size != 0) {
                TreeNode cur = queue.poll();
                //curList.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(0, curList);
        }

        return ret;
    }

    //根据后序遍历和中序遍历构建二叉树
//    public int postIndex = 0;
//    public TreeNode buildTree(int[] inorder, int[] postorder) {
//        postIndex = postorder.length - 1;
//        return buildTreeChild(postorder, inorder, 0, inorder.length - 1);
//    }
//    public TreeNode buildTreeChild(int[] postorder, int[] inorder, int inbegin, int inend) {
//        if (inbegin > inend) {
//            return null;
//        }
//        TreeNode root = new TreeNode(postorder[postIndex]);
//        int rootIndex = findIndex(inorder, inbegin, inend, postorder[postIndex]);
//        postIndex--;
//
//        root.right = buildTreeChild(postorder, inorder, rootIndex + 1, inend);
//        root.left = buildTreeChild(postorder, inorder, inbegin, rootIndex - 1);
//
//        return root;
//    }
//
//    private int findIndex(int[] inorder, int inbegin, int inend, int key) {
//        for (int i = inbegin; i <= inend; i++) {
//            if (inorder[i] == key) {
//                return i;
//            }
//        }
//        return -1;
//    }


    //前序和中序遍历
//    public int preIndex = 0;
//    public TreeNode buildTree(int[] preorder, int[] inorder) {
//
//        return buildTreeChild(preorder,inorder,0,inorder.length-1);
//    }
//    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend){
//        if(inbegin > inend){
//            return null;
//        }
//        TreeNode root = new TreeNode(preorder[preIndex]);
//        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);
//
//        preIndex++;
//
//        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
//        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
//
//        return root;
//    }
//    private int findIndex(int[] inorder,int inbegin,int inend,int key){
//        for(int i = inbegin;i <= inend ; i++){
//            if(inorder[i] == key){
//                return i;
//            }
//        }
//        return -1;
//    }
//
    //二叉树的最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }

        if (root == p || root == q) {
            return root;
        }

        TreeNode leftT = lowestCommonAncestor(root.left, p, q);
        TreeNode rightT = lowestCommonAncestor(root.right, p, q);

        if (leftT != null && rightT != null) {
            return root;
        } else if (leftT != null) {
            return leftT;
        } else if (rightT != null) {
            return rightT;
        }

        return null;
    }


    //找到root到指定节点node路径上的所有节点，存储到stack当中
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null) {
            return false;
        }
        stack.push(root);

        if (root == node) {
            return true;
        }

        boolean flg = getPath(root.left, node, stack);
        if (flg) {
            return true;
        }

        flg = getPath(root.right, node, stack);
        if (flg) {
            return true;
        }
        stack.pop();
        return false;
    }

    //二叉树的公共祖先（进阶版）
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root, p, stack1);
        getPath(root, q, stack2);
        //上述代码已经能够求到root到指定节点路径上的所有节点
        int size1 = stack1.size();
        int size2 = stack2.size();
        int size = size1 - size2;
        if (size < 0) {
            size = Math.abs(size);
            while (size != 0) {
                stack2.pop();
                size--;
            }
        } else {
            while (size != 0) {
                stack1.pop();
                size--;
            }
        }
        //两个栈的大小是一样的了
        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            if (stack1.peek() == stack2.peek()) {
                return stack1.pop();
            } else {
                stack1.pop();
                stack2.pop();
            }
        }
        return null;
    }

    //根据二叉树创建字符串
    public String tree2str(TreeNode root) {
        StringBuilder StringBuilder = new StringBuilder();
        tree2strChild(root, StringBuilder);
        return StringBuilder.toString();
    }

    public void tree2strChild(TreeNode root, StringBuilder StringBuilder) {
        if (root == null) {
            return;
        }
        StringBuilder.append(root.val);

        //判断左子树
        if (root.left != null) {
            StringBuilder.append("(");
            tree2strChild(root.left, StringBuilder);
            StringBuilder.append(")");
        } else {
            if (root.right == null) {
                return;
            } else {
                StringBuilder.append("()");
            }
        }

        //判断右子树
        if (root.right != null) {
            StringBuilder.append("(");
            tree2strChild(root.right, StringBuilder);
            StringBuilder.append(")");
        } else {
            return;
        }
    }

    //前序遍历（非递归）
//    public List<Integer> preorderTraversal(TreeNode root) {
//        List<Integer> List = new ArrayList<>();
//
//        if(root == null){
//            return List;
//        }
//
//
//        Stack<TreeNode> Stack = new Stack();
//        TreeNode cur = root;
//        TreeNode top = null;
//
//        while(cur != null || !Stack.isEmpty()){
//            while(cur != null){
//                Stack.push(cur);
//                List.add(cur.val);
//                cur = cur.left;
//            }
//            top = Stack.pop();
//            cur = top.right;
//        }
//
//        return List;
//    }

    //后序排遍历非递归

//    public List<Integer> postorderTraversal(TreeNode root) {
//        List<Integer> List = new ArrayList<>();
//
//        if (root == null) {
//            return List;
//        }
//
//        Stack<TreeNode> Stack = new Stack();
//        TreeNode cur = root;
//        TreeNode top = null;
//        TreeNode prev = null;
//
//        while (cur != null || !Stack.isEmpty()) {
//            while (cur != null) {
//                Stack.push(cur);
//                cur = cur.left;
//
//            }
//            top = Stack.peek();
//            if (top.right == null || top.right == prev) {
//                Stack.pop();
//                List.add(top.val);
//                prev = top;
//            } else {
//                cur = top.right;
//            }
//
//        }
//        return List;
//    }

}